﻿using System;

namespace SalesSys.Comm.Utility
{
    public class DateTimeEx
    {
        /// <summary>
        /// 生成时间戳,1970到现在的秒数
        /// </summary>
        /// <returns></returns>
        public static long GenerateTimeStamp()
        {
            return GenerateTimeStamp(new DateTime(1970, 1, 1, 0, 0, 0, 0));
        }
        /// <summary>
        /// 生成时间戳,指定时间到现在的秒数
        /// </summary>
        /// <returns></returns>
        public static long GenerateTimeStamp(DateTime dt)
        {
            TimeSpan ts = DateTime.UtcNow - dt;
            return Convert.ToInt64(ts.TotalSeconds);
        }
        /// <summary>
        /// 尝试转化为时间类型,失败返回null
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime? TryParse(string str)
        {
            DateTime dt;
            if (DateTime.TryParse(str, out dt))
            {
                return dt;
            }
            return null;
        }

        /// <summary>
        /// 将指定的秒数转换为时间长度
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns></returns>
        public static TimeSpan SecondsToTimeSpan(int seconds)
        {
            return new TimeSpan(0, 0, 0, seconds);
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        public static DateTime TimestampToDate(string timeStamp)
        {
            DateTime dtStart = new DateTime(1970, 1, 1);
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        public static int DateToTimestamp(System.DateTime time)
        {
            System.DateTime startTime = new System.DateTime(1970, 1, 1);
            return (int)(time - startTime).TotalSeconds;
        }
    }
}
